<template lang="html">
  <div class='login'>
    <el-form :model="loginForm" :rules="loginRule" ref="loginForm" style="width:250px;height:180px;margin:0 auto 0;">
      <el-form-item prop="loginName" style="margin-top: 60px;margin-bottom: 40px;">
        <el-input type="text" v-model="loginForm.loginName" auto-complete="on" placeholder="账户" @focus="showTip" @blur="hiddenTip"></el-input>
        <ul class="login-suggest" v-if="tipshow">
          <!-- <li class="pre-history"><p><span>历史记录</span></p></li> -->
          <li v-for="(item,index) in historylist" class="list" @click="historyOk(item)" @mouseover="keyChange" @mouseout="keyChange">
            <span>{{item}}</span>
          </li>
        </ul>
      </el-form-item>
      <el-form-item prop="password" style="margin-bottom: 40px;">
        <el-input type="password" v-model="loginForm.password" auto-complete="off" placeholder="密码"></el-input>
      </el-form-item>
      <!-- <el-form-item prop="user_id">
        <div id="captcha-box"></div>
        <div id="loading-tip">加载中，请稍后...</div>
      </el-form-item> -->
      <!-- <el-form-item prop="captcha">
        <div style="text-align:left;">
          <el-input type="text" v-model="loginForm.captcha" auto-complete="off" placeholder="验证码" size="medium" style="width:50%;"></el-input>
          <img :src="captcha_img" alt="captcha" @click="$store.dispatch('captcha')">
        </div>
      </el-form-item> -->
    </el-form>
  </div>
</template>

<script>
  import {
    get,
    post,
    common,
    getRefresh
  } from "../../api/api";
  import {
    Loading
  } from "element-ui";
  import gtInit from "../../../static/gt.js";
  import axios from "axios";
  import qs from "qs";

  export default {
    name: "login",
    inject: ['reload'],
    data() {
      var checkLoginName = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入用户名"));
        } else if (value.match(/^1[34578]\d{9}$/g) == null) {
          callback(new Error("必须手机号码!"));
        } else {
          callback();
        }
      };
      var checkPassword = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入密码"));
        } else if (value.length < 6 || value.length > 12) {
          callback(new Error("必须6-12个字符!"));
        } else {
          callback();
        }
      };
      var checkRepeatPassword = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.findUserform.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      var checkCaptcha = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入验证码"));
        } else {
          callback();
        }
      };
      return {
        active: "login",
        checked: true,
        historylist: [],
        historyKey: false,
        tipshow: false,
        loginForm: {
          loginName: "",
          password: "",
          // user_id: ""
        },
        loginRule: {
          loginName: [{
              required: true,
              message: "请输入账户",
              triggle: "blur"
            }
            // {
            //   pattern: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$|^1[34578]\d{9}$/,
            //   message: "请输入正确的手机或邮箱",
            //   triggle: "blur"
            // }
          ],
          password: [{
              required: true,
              message: "请输入密码",
              triggle: "blur"
            },
            {
              min: 6,
              max: 30,
              message: "必须6-30个字符",
              triggle: "blur"
            }
          ],
          user_id: [{
            required: true,
            message: "请输入验证码",
            triggle: "blur",
            type: 'number'
          }]
        },
        findDialogVisible: false,
        findForm: {
          email: "",
          phone: ""
        },
        findUserform: {
          loginName: "",
          password: "",
          repeatPassword: "",
          captcha: ""
        },
        findUserRule: {
          loginName: [{
            validator: checkLoginName,
            trigger: "blur"
          }],
          password: [{
            validator: checkPassword,
            trigger: "blur"
          }],
          repeatPassword: [{
            validator: checkRepeatPassword,
            trigger: "blur"
          }],
          captcha: [{
            validator: checkCaptcha,
            trigger: "blur"
          }]
        },
        showPassword: true,
        keyboard: ""
      };
    },
    computed: {
      captcha_img() {
        return this.$store.state.Auth.captcha_img;
      }
    },
    methods: {
      //手动登录
      postLogin() {
        // this.$router.push({
        //           path: '/manage_system/statsInfo',
        //         });
        this.$refs['loginForm'].validate(valid => {
          if (valid) {
            post("/manager/login", this.loginForm)
              .then(resdata => {
                let data = resdata.data;
                let _this = this;
                let error = function () {
                  this.$message({
                    message: resdata.msg,
                    type: "error"
                  });
                  this.$store.dispatch("captcha");
                  this.$store.commit("set_auth_loading", false);
                }.bind(this);
                let success = function () {
                  this.$store.state.Auth.userInfo = {
                    group: data.group,
                    role: data.role,
                    info: data.info
                  };
                  // sessionStorage.setItem(
                  //   "person_info",
                  //   JSON.stringify(data.info)
                  // );
                  this.$store.state.Auth.person_info = data.info;
                  this.$store.state.Auth.loginName = this.loginForm.loginName;
                  //判断历史账号的数量与值
                  let hkey = 0;
                  this.historylist.forEach(function (element) {
                    if (this.loginForm.loginName === element) {
                      hkey++;
                    }
                  }, this);
                  if (hkey == 0) {
                    if (this.historylist.length == 4) {
                      this.historylist.reverse().splice(0, 1);
                      this.historylist.push(this.loginForm.loginName);
                    } else {
                      this.historylist.reverse().push(this.loginForm.loginName);
                    }
                  }
                  localStorage.setItem(
                    "historylist",
                    JSON.stringify(this.historylist)
                  );
                  var userInfo = {
                    'nickName': data.nickName,
                    'loginName': data.loginName,
                    'photoUrl': data.photoUrl
                  }
                  localStorage.setItem(
                    "userInfo",
                    JSON.stringify(userInfo)
                  );
                  //------------
                  const loading = this.$loading({
                    lock: true,
                    text: "Loading",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 1)"
                  });
                  // setTimeout(() => {
                  //   this.$store.dispatch("permission", loading).then(() => {
                  //     // loading.close();
                  //   });
                  // }, 2000);
                  setTimeout(() => {
                    _this.getPermissionListByUid(loading)
                    // loading.close();
                  }, 2100);
                  if (this.checked) {
                    localStorage.setItem("token", data.token);
                  } else {
                    if (localStorage.getItem("token"))
                      localStorage.removeItem("token");
                  }
                }.bind(this);
                common()(error)(success)(resdata);
                if (resdata.code == 110001) {
                  this.$message({
                    message: resdata.msg,
                    type: "error"
                  });
                }
                this.$store.commit("set_auth_loading", false);
                this.$store.commit("islogin", 1);
                sessionStorage.setItem("islogin", true);
                sessionStorage.setItem("loginName", this.loginForm.loginName);
              })
              .catch(e => {
                this.$message({
                  message: e,
                  type: "error"
                });
                this.$store.commit("set_auth_loading", false);
              });
          } else {
            this.$notify.error({
              title: "错误",
              message: "请输入正确的用户名与密码并进行验证",
              offset: 100
            });
            this.$store.commit("set_auth_loading", false);
            return false;
          }
        });
      },
      //手动登录触发器
      handleSubmit() {
        this.$store.commit("set_auth_loading", true);
        this.postLogin();
      },
      //提示框的显示与隐藏
      showTip() {
        if (this.historylist.length != 0) {
          this.tipshow = true;
        }
      },
      hiddenTip() {
        if (this.historyKey == false) {
          this.tipshow = false;
        } else {}
      },
      //使用历史记录
      historyOk(name) {
        this.loginForm.loginName = name;
        this.tipshow = false;
        this.historyKey = !this.historyKey;
      },
      keyChange() {
        this.historyKey = !this.historyKey;
      },
      findOnSubmit() {},
      getCaptcha() {
        this.$refs.findUserform.validateField("loginName", valid => {
          if (!valid) {
            post("auth/captcha", {
              loginName: this.findUserform.loginName,
              type: 1
            }).then(resdata => {
              let self = function () {
                getRefresh(this.getCaptcha);
              }.bind(this);
              let error = function () {
                alert(resdata.msg);
              }.bind(this);
              let success = function () {
                console.log(resdata);
                alert(resdata.msg);
              }.bind(this);
              common(self)(error)(success)(resdata);
            });
          } else {
            alert("请输入手机号!!");
            return false;
          }
        });
      },
      nextStep() {
        this.$refs.findUserform.validate(valid => {
          if (valid) {
            let param = {};
            param.loginName = this.findUserform.loginName;
            param.password = this.findUserform.password;
            param.captcha = this.findUserform.captcha;
            post("auth/reset", param).then(resdata => {
              let self = function () {
                getRefresh(this.nextStep);
              }.bind(this);
              let error = function () {
                alert(resdata.msg);
              }.bind(this);
              let success = function () {
                console.log(resdata);
                alert(resdata.msg);
                this.showPassword = fasle;
              }.bind(this);
              common(self)(error)(success)(resdata);
            });
          } else {
            alert("error submit!!");
            return false;
          }
        });
      },
      preStep() {
        this.showPassword = !this.showPassword;
      },

      //行为验证初始化函数
      geetest() {
        const this_ = this;
        const user_id = new Date().getTime();
        axios
          .post(
            //"http://192.168.1.226:6688/api/test/gt3-1",
            "https://www.etontech.top:6691/api/auth/gt3Init",
            qs.stringify({
              user_id: user_id
            })
          )
          .then(resdata => {
            var data = JSON.parse(resdata.data.data);
            console.log(data);
            //请检测data的数据结构， 保证data.gt, data.challenge, data.success有值
            window.initGeetest({
                // 以下配置参数来自服务端 SDK
                gt: data.gt,
                challenge: data.challenge,
                offline: !data.success,
                new_captcha: true,
                width: "100%"
              },
              function (captchaObj) {
                // 这里可以调用验证实例 captchaObj 的实例方法
                captchaObj.appendTo("#captcha-box");
                captchaObj.onReady(function () {
                  // DOM 准备好后，隐藏 #loading-tip 元素
                  // 仅作示例用，用您适合的方式隐藏即可
                  document.getElementById("loading-tip").style.display = "none";
                });
                captchaObj.onSuccess(function () {
                  var result = captchaObj.getValidate();

                  // ajax 伪代码，进行二次验证
                  axios
                    .post(
                      //"http://192.168.1.226:6688/api/test/gt3-2",
                      "https://www.etontech.top:6691/api/web/gt3Validate", {
                        geetest_challenge: result.geetest_challenge,
                        geetest_validate: result.geetest_validate,
                        geetest_seccode: result.geetest_seccode
                        // 其他服务端需要的数据，比如登录时的用户名和密码
                      })
                    .then(resdata => {
                      // 根据服务端二次验证的结果进行跳转等操作
                      console.log(resdata);
                      this_.loginForm.user_id = user_id;
                    });
                });
              }
            );
          });
      },
      //---------权限渲染菜单--------
      getPermissionListByUid(loading) {
        return new Promise((resolve, reject) => {
          post("/perm/xasPermissionListByUid").then(resdata => {
            let self = function () {
              getRefresh(this.getPermissionListByUid);
            }.bind(this);
            let error = function () {
              alert(resdata.msg)
            }.bind(this);
            let success = function () {
              if (resdata.code == 1) {
                var PermissionList = resdata.data;
                var PermissPath = false;
                localStorage.setItem("permissionList", JSON.stringify(resdata.data));
                for (var i = 0; i < PermissionList.length; i++) {
                  for (var j = 0; j < PermissionList[i].xasPermission.length; j++) {
                    if (PermissionList[i].xasPermission[j].id == 102) {
                      PermissPath = true;
                    }
                  }
                }
                if (PermissPath) {
                  this.$router.push({
                    name: '统计信息',
                    params: {
                      permissionList: PermissionList
                    }
                  });
                } else {
                  this.$router.push({
                    name: PermissionList[0].xasPermission[0].name,
                    params: {
                      permissionList: PermissionList
                    }
                  });
                }
                setTimeout(() => {
                  this.$router.go(0); 
                  // this.reload();
                  loading.close();
                }, 1000);
              } else {
                alert("无数据!");
              }
            }.bind(this);
            common(self)(error)(success)(resdata);
            resolve();
          });
        });
      },
    },
    mounted() {
      // this.geetest();
      this.historylist = JSON.parse(localStorage.getItem("historylist")) ?
        JSON.parse(localStorage.getItem("historylist")).reverse() : [];
    },
    created() {},
    watch: {
      "loginForm.username": function () {
        this.tipshow = false;
        if (this.loginForm.username === "") {
          this.tipshow = true;
        }
      }
    }
  };

</script>

<style lang="scss">
  .login {
    // overflow: hidden;
    margin-top: 0px;
    .geetest_holder.geetest_wind {
      min-width: 250px !important;
    }
    .el-input {
      width: 250px;
    }
    a {
      color: #fff;
      text-decoration: none;
    }
    img {
      height: 36px;
      width: 120px;
      margin-left: 5px;
      position: absolute;
      top: 2px;
      border-radius: 3px;
    }
    .login-suggest {
      display: block;
      position: absolute;
      list-style: none;
      width: 250px;
      border: 1px solid #e5e9ef;
      margin: 2px 0px 0px 0px;
      padding: 0px 0px 5px 0px;
      background: #fff;
      z-index: 99999;
      font-size: 1.6rem;
      box-sizing: border-box;
    }
    .login-suggest .list {
      height: 30px;
      line-height: 30px;
      text-align: left;
      cursor: default;
      span {
        display: inline-block;
        margin-left: 10px;
      }
    }
    .login-suggest .list:hover {
      background: #ecebeb;
    }
    .pre-history p {
      margin: 0;
      padding: 0;
      text-align: center;
      height: 18px;
      line-height: 18px;
    }
    .pre-history span {
      height: 18px;
    }
    .el-tabs__item {
      padding: 0 !important;
      width: 100px;
    }
    .el-tabs__active-bar {
      width: 100px !important;
    }
    .find:hover {
      text-decoration: underline;
    }
    .findGroupDialog {
      .el-dialog {
        box-shadow: 0px 5px 15px 0 rgba(0, 0, 0, 0.5);
        border-radius: 5px;
        margin-top: 30vh !important;
        .el-dialog__header {
          text-align: left;
          .el-dialog__title {
            font-family: "Roboto", sans-serif;
            color: #7d7d7d;
            font-size: 15px;
          }
        }
        .el-dialog__body {
          min-height: 246px;
          .el-form {
            padding-left: 40px;
            .el-form-item {
              width: 80%;
              .el-form-item__content {
                text-align: left;
              }
              .el-form-item__label {
                padding: 0 24px 0 0;
                color: #333;
                font-weight: 400;
                font-size: 13px;
              }
            }
          }
        }
      }
    }
  }

</style>
